package com.hello;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;

import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.hello.resources.ContactAccessor;
import com.hello.resources.ContactInfo;
import com.hello.resources.SoundManager;

public class SensSmsScreen extends Activity {
	private SoundManager mSoundManager;// in order to add sound to buttons
	public void setWallpaper() {
		Drawable wallpaper = WallpaperManager.getInstance(this).getDrawable();
		if (wallpaper == null) {
			try {
				clearWallpaper();
			} catch (IOException e) {
				Toast.makeText(this, e.getMessage(), 3).show();
			}
		} else {
			wallpaper.setColorFilter(R.color.gray,Mode.DARKEN);
			getWindow().setBackgroundDrawable(wallpaper);
		}
	}

	private DrunkoidSettingData settings = DrunkoidSettingData.getInstance();
	private String phoneNo = "";
	SendEmergencySms emergenySmsSender;
	AtomicBoolean isChangedByUser;

	Button btnSendSMS;
	EditText textPhoneNumber;
	EditText textMessage;
	Button btnAddContact;
	
	// Request code for the contact picker activity
	private static final int PICK_CONTACT_REQUEST = 1;
	private final ContactAccessor mContactAccessor = ContactAccessor.getInstance();
	private LocationManager locationManager;
	 LocationListener locationListener;


	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sms);
		setWallpaper();
		// Emergency SMS 
		emergenySmsSender = new SendEmergencySms(this);
		setContentView(R.layout.sms);
		isChangedByUser = new AtomicBoolean(false);

		btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
		textPhoneNumber = (EditText) findViewById(R.id.txtPhoneNo);
		textMessage = (EditText) findViewById(R.id.txtMessage);
		btnAddContact = (Button) findViewById(R.id.AddContactSmsScreen);

		mSoundManager = new SoundManager();
		mSoundManager.initSounds(getBaseContext());
		mSoundManager.addSound(1, R.raw.comedy_zips_pops_and_bonks);
		mSoundManager.addSound(2, R.raw.sound);
		mSoundManager.addSound(3,R.raw.piggy_bank_shake);
		textMessage.setText(R.string.sendSmsMessageText);
		textMessage.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				isChangedByUser.set(true);
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		});
	    locationListener = new LocationListener() {
	        public void onLocationChanged(Location location) {
	        	if (!isChangedByUser.get())
	        		UpdateLocation(location);
	        }

	        public void onProviderDisabled(String provider) {
	            
	        }

	        public void onProviderEnabled(String provider) {
	        }

	        public void onStatusChanged(String provider, int status, Bundle extras) {
	        }
	    };
	    
		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		
		Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        String provider = locationManager.NETWORK_PROVIDER;
        Location location = locationManager.getLastKnownLocation(provider);
        UpdateLocation(location);
        locationManager.requestLocationUpdates(provider, 0, 0, locationListener); 	

		btnSendSMS.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v) 
			{                
				mSoundManager.playSound(3);

				if ("".equals(phoneNo)){
					phoneNo = textPhoneNumber.getText().toString();
				}
				String message = textMessage.getText().toString();

				if (phoneNo.length()>0 && message.length()>0)
				{
					emergenySmsSender.sendSMS(phoneNo, message);
					//return to last screen
					Intent intent = new Intent();
					setResult(RESULT_OK, intent);
					finish();
				}
				else
					Toast.makeText(getBaseContext(), 
							R.string.sendSmsInstruction, 
							Toast.LENGTH_SHORT).show();
				
			}
		});
		btnAddContact.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v) 
			{                
				mSoundManager.playSound(3);
				pickContact();
			}
		});

	}
	
	private void UpdateLocation(Location location) {
		String addressString= "";
        if (location != null) {
        	double lat = location.getLatitude();
            double lng = location.getLongitude();
            Geocoder gc = new Geocoder(this, Locale.getDefault());

            try {

                List<Address> addresses = gc.getFromLocation(lat, lng, 1);
                StringBuilder sb = new StringBuilder();

                if (addresses.size() > 0) {
                    Address address = addresses.get(0);

                    for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
                        sb.append(address.getAddressLine(i)).append(" ");

                    //sb.append(address.getCountryName());
                }
                addressString = sb.toString();
            } catch (IOException e) {
            	String s = e.getMessage();
            }
        }
        //String msg = (String)gt (R.string.sendSmsMessageText);
		if (!addressString.trim().equalsIgnoreCase("")){
			textMessage.setText( R.string.sendSmsMessageText);
			textMessage.append("I'm at " + addressString);
		}	
	}

    
	/**
	 * Click handler for the Pick Contact button.  Invokes a contact picker activity.
	 * The specific intent used to bring up that activity differs between versions
	 * of the SDK, which is why we delegate the creation of the intent to ContactAccessor.
	 */
	protected void pickContact() {
		startActivityForResult(mContactAccessor.getPickContactIntent(), PICK_CONTACT_REQUEST);
	}

	/**
	 * Invoked when the contact picker activity is finished. The {@code contactUri} parameter
	 * will contain a reference to the contact selected by the user. We will treat it as
	 * an opaque URI and allow the SDK-specific ContactAccessor to handle the URI accordingly.
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PICK_CONTACT_REQUEST && resultCode == RESULT_OK) {
			loadContactInfo(data.getData());
		}
	}

	/**
	 * Load contact information on a background thread.
	 */
	private void loadContactInfo(Uri contactUri) {

		/*
		 * We should always run database queries on a background thread. The database may be
		 * locked by some process for a long time.  If we locked up the UI thread while waiting
		 * for the query to come back, we might get an "Application Not Responding" dialog.
		 */
		AsyncTask<Uri, Void, ContactInfo> task = new AsyncTask<Uri, Void, ContactInfo>() {

			@Override
			protected ContactInfo doInBackground(Uri... uris) {
				return mContactAccessor.loadContact(getContentResolver(), uris[0]);
			}

			@Override
			protected void onPostExecute(ContactInfo result) {
				settings.setSmsContact(result);
				phoneNo = result.getPhoneNumber();
				SensSmsScreen.this.textPhoneNumber.setText(result.getDisplayName() + " " + result.getPhoneNumber());
			}
		};

		task.execute(contactUri);
	}
	@Override
	public void onStop(){
		locationManager.removeUpdates(locationListener);
		super.onStop();
		
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
	}

	

}